package popple.display
{
	import flash.display.BitmapData;
	import flash.display3D.Context3D;
	import flash.display3D.Context3DTextureFormat;
	import flash.display3D.VertexBuffer3D;
	import flash.display3D.textures.Texture;
	import flash.geom.Rectangle;
	
	import popple.core.RenderHelper;
	import popple.data.StaticData;

	/**
	 * 显示对象源
	 * @author popplecui
	 * 
	 */	
	public class TBitmap
	{
		private var _uvData:Vector.<Number>;
		private var _helper:RenderHelper;
		public var bitmapData:BitmapData;
		public var width:Number;
		public var height:Number;
		public var rect:Rectangle;
		
		public var texture:Texture;
		public var uv:VertexBuffer3D;
		/**
		 * 
		 * @param bd 位图源
		 * @param rect 显示区域
		 * 
		 */		
		public function TBitmap(bd:BitmapData=null,rect:Rectangle=null)
		{
			_helper=RenderHelper.getInstance();
			this.bitmapData=bd;
			this.rect=rect;
			initialize();
		}
		public function setBitmap(bd:BitmapData,rect:Rectangle=null):void
		{
			this.bitmapData=bd;
			this.rect=rect;
			initialize();
		}
		protected function initialize():void
		{
			if(this.bitmapData!=null)
			{
				if(this.rect!=null)
				{
					
					
					var width:uint=this.bitmapData.width;
					var height:uint=this.bitmapData.height;
					
					this.width=rect.width;
					this.height=rect.height;
					
					if(rect.width!=0&&rect.height!=0)
					{
						
						this._uvData=new Vector.<Number>(8);
						this._uvData[0]=this.rect.x/width;
						this._uvData[1]=this.rect.y/height;
						this._uvData[2]=(this.rect.x+this.rect.width)/width;
						this._uvData[3]=this.rect.y/height;
						this._uvData[4]=(this.rect.x+this.rect.width)/width;
						this._uvData[5]=(this.rect.y+this.rect.height)/height;
						this._uvData[6]=this.rect.x/width;
						this._uvData[7]=(this.rect.y+this.rect.height)/height;
					}
					else
					{
						this._uvData=StaticData.uv;
					}
				}
				else
				{
					this._uvData=StaticData.uv;
					this.width=this.bitmapData.width;
					this.height=this.bitmapData.height;
					
				}
				this.uv=_helper.getVertexBuffer(this._uvData,2);
				this.texture=_helper
					   .getTexture(this.bitmapData,Context3DTextureFormat.BGRA,true);
				
			}
		}
		
		public function dispose():void
		{
			if(this.bitmapData!=null)
			_helper.removeTexture(this.bitmapData);
			this._helper.removeVertexBuffer(this._uvData);
			this.bitmapData.dispose();
			this.bitmapData=null;
			this._uvData.length=0;
			this._uvData=null;
			
		}
	}
}